﻿@page "/project/{Id}"

@inject IPageModelCatche<ProjectViewModel> _pageModelCatche
@inject NavigationManager NavigationManager
@implements IDisposable

<CnGalWebSite.ProjectSite.Shared.Components.Shared.TitleCard Title="@Model?.Name" />

@if(isNotFound)
{
    <NotFoundCard Page/>
}
else
{
    @if (Model != null)
{
    <MRow>
        <MCol Cols="12" Md="4" Lg="3">
            <CnGalWebSite.ProjectSite.Shared.Components.Projects.MainCards.InfoCard Model="Model" />
        </MCol>
        <MCol Cols="12" Md="8" Lg="9">
            <CnGalWebSite.ProjectSite.Shared.Components.Projects.MainCards.DescriptionCard Model="Model" />
            <CnGalWebSite.ProjectSite.Shared.Components.Projects.MainCards.ImageCard Model="Model" />
            <CnGalWebSite.ProjectSite.Shared.Components.Projects.MainCards.PositionGroupCard Model="Model" OnChanged="OnChanged" />
            <CnGalWebSite.ProjectSite.Shared.Components.Projects.MainCards.PositionUserGroupCard Model="Model" OnChanged="OnChanged" />
        </MCol>
    </MRow>
}
else
{
    <CnGalWebSite.Components.Progressings.ProgressingCard Page />
}

}


@code {
    [Parameter]
    public string Id { get; set; }

    [Parameter]
    public string Type { get; set; }

    ProjectViewModel Model;

    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    bool isNotFound;

    protected override async Task OnInitializedAsync()
    {
        NavigationManager.LocationChanged -= OnLocationChanged;
        NavigationManager.LocationChanged += OnLocationChanged;

        await Refresh();
    }

    public async Task Refresh(int tab = 0)
    {
        try
        {
            Model = await _pageModelCatche.GetCache($"api/project/get?id={Id}");
            if (tab != 0)
            {
                Model.TabIndex = tab;
            }
            StateHasChanged();
        }
        catch (Exception ex)
        {
            isNotFound = true;
            //await ErrorHandler.ProcessError(ex, "获取企划数据失败");
        }
    }

    public async Task OnChanged()
    {
        var model = await _pageModelCatche.GetCache($"api/project/get?id={Id}");
        var tab = model.TabIndex;
        _pageModelCatche.Clean($"api/project/get?id={Id}");
        await Refresh(tab);
    }

    public async void OnLocationChanged(object sender, LocationChangedEventArgs args)
    {
        await Refresh();
    }


    public void Dispose()
    {
        NavigationManager.LocationChanged -= OnLocationChanged;
        GC.SuppressFinalize(this);
    }

}
